﻿using System;
using System.Collections.Generic;
using System.ComponentModel.Composition;
using System.ComponentModel.Composition.Hosting;
using System.ComponentModel.Composition.Primitives;
using System.Linq;
using Caliburn.Micro;
using PocketBook.Model;
using PocketBook.ViewModels;
using PocketBook.ViewModels.Designs;

namespace PocketBook
{
    public class AppBootstrapper : Bootstrapper<IShell>
    {
        CompositionContainer _container;

        protected override void Configure()
        {
            var catalog = new AggregateCatalog(AssemblySource.Instance.Select(x => new AssemblyCatalog(x)).OfType<ComposablePartCatalog>());

            _container = new CompositionContainer(catalog);

            var batch = new CompositionBatch();

            batch.AddExportedValue<ILayoutMetrics>(new LayoutMetrics());
            batch.AddExportedValue<IPrintService>(new PrintService());
            batch.AddExportedValue<IWindowManager>(new WindowManager());
            batch.AddExportedValue<IEventAggregator>(new EventAggregator());
            batch.AddExportedValue(_container);
            batch.AddExportedValue(catalog);

            _container.Compose(batch);

            ConfigureViewLocator();

            Book.DefaultDesign = () => new BlankPage();
        }

        protected override object GetInstance(Type serviceType, string key)
        {
            var contract = string.IsNullOrEmpty(key) ? AttributedModelServices.GetContractName(serviceType) : key;
            var exports = _container.GetExportedValues<object>(contract);

            if (exports.Any())
                return exports.First();

            throw new Exception(string.Format("Could not locate any instances of contract {0}.", contract));
        }

        protected override IEnumerable<object> GetAllInstances(Type serviceType)
        {
            return _container.GetExportedValues<object>(AttributedModelServices.GetContractName(serviceType));
        }

        protected override void BuildUp(object instance)
        {
            _container.SatisfyImportsOnce(instance);
        }

        private static void ConfigureViewLocator()
        {
            var defaultLocator = ViewLocator.LocateTypeForModelType;

            ViewLocator.LocateTypeForModelType = (modelType, displayLocation, context) =>
            {
                var result = defaultLocator(modelType, displayLocation, context);
                if (result != null) return result;

                if (modelType.FullName == null || !typeof(IDesign).IsAssignableFrom(modelType)) return null;

                var viewTypeName = modelType.FullName.Replace(".ViewModels", ".Views") + "View";

                var viewType = AssemblySource.Instance
                    .SelectMany(assembly => assembly.GetExportedTypes().Where(type => type.FullName == viewTypeName))
                    .FirstOrDefault();

                return viewType;
            };
        }
    }
}